package com.qidianit.mes.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @company 起点编程
 * @author 戴着假发的程序员
 * @date 2025/7/22 10:44
 * @description 格式化工具类，提供日期、JSON等格式化方法
 */
public class FormatterUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 格式化日期为字符串
     * @param date 日期对象
     * @return 格式化后的字符串
     */
    public static String formatDate(Date date) {
        return dateFormat.format(date);
    }

    /**
     * 将对象转换为JSON字符串
     * @param object 对象
     * @return JSON字符串
     */
    public static String toJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON转换失败", e);
        }
    }

    /**
     * 将JSON字符串转换为对象
     * @param jsonString JSON字符串
     * @param clazz 目标类
     * @return 对象
     */
    public static <T> T fromJsonString(String jsonString, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }
    // 将JSON字符串转换为List
    public static <T> List<T> fromJsonToList(String jsonString, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonString, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    /**
     * 将JSON字符串转换为集合
     * @param jsonString JSON字符串
     * @param collectionClass 集合类型
     * @param elementClasses 集合元素类型
     * @return 集合对象
     */
    public static <T> T fromJsonToCollection(String jsonString, Class<T> collectionClass, Class<?>... elementClasses) {
        try {
            return objectMapper.readValue(jsonString, objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }
}